<template>
  <div class="page-editor">
    <!-- 顶部工具栏 -->
    <div class="editor-header">
      <div class="left">
        <el-button @click="handleBack">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
        <el-input
          v-model="pageData.title"
          placeholder="页面标题"
          style="width: 200px; margin: 0 16px" />
      </div>
      <div class="center">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="pc">PC端</el-radio-button>
          <el-radio-button label="mobile">移动端</el-radio-button>
        </el-radio-group>
      </div>
      <div class="right">
        <el-button @click="handlePreview">
          <el-icon><View /></el-icon>
          预览
        </el-button>
        <el-button type="primary" @click="handleSave">
          <el-icon><Check /></el-icon>
          保存
        </el-button>
      </div>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-main">
      <!-- 组件列表 -->
      <div class="component-list">
        <el-tabs>
          <el-tab-pane label="基础组件">
            <draggable
              :list="basicComponents"
              :group="{ name: 'components', pull: 'clone', put: false }"
              :sort="false"
              :clone="handleClone"
              item-key="type">
              <template #item="{ element }">
                <div class="component-item">
                  <el-icon><component :is="element.icon" /></el-icon>
                  <span>{{ element.label }}</span>
                </div>
              </template>
            </draggable>
          </el-tab-pane>
          <el-tab-pane label="高级组件">
            <draggable
              :list="advancedComponents"
              :group="{ name: 'components', pull: 'clone', put: false }"
              :sort="false"
              :clone="handleClone"
              item-key="type">
              <template #item="{ element }">
                <div class="component-item">
                  <el-icon><component :is="element.icon" /></el-icon>
                  <span>{{ element.label }}</span>
                </div>
              </template>
            </draggable>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 画布区域 -->
      <div class="canvas">
        <!-- 标尺容器 -->
        <div class="ruler-container">
          <!-- 标尺交叉点 -->
          <div class="ruler-corner">
            <el-icon><Position /></el-icon>
          </div>
          <!-- 水平标尺 -->
          <div class="ruler ruler-h" ref="rulerH">
            <canvas ref="rulerHCanvas"></canvas>
            <div class="ruler-indicator" :style="{ left: mouseX + 'px' }" v-show="showIndicator">
              <div class="ruler-line"></div>
              <div class="ruler-indicator-value">{{ mouseX }}px</div>
            </div>
          </div>
          <!-- 垂直标尺 -->
          <div class="ruler ruler-v" ref="rulerV">
            <canvas ref="rulerVCanvas"></canvas>
            <div class="ruler-indicator" :style="{ top: mouseY + 'px' }" v-show="showIndicator">
              <div class="ruler-line"></div>
              <div class="ruler-indicator-value">{{ mouseY }}px</div>
            </div>
          </div>
        </div>

        <!-- 画布内容 -->
        <div class="canvas-wrapper" :class="viewMode">
          <div class="canvas-container" ref="canvasRef">
            <draggable
              v-model="pageData.components"
              :group="{ name: 'components' }"
              item-key="id"
              class="canvas-content"
              :animation="150"
              @start="handleDragStart"
              @end="handleDragEnd">
              <template #item="{ element }">
                <component-wrapper
                  :component="element"
                  :selected="selectedComponent?.id === element.id"
                  @select="handleSelectComponent"
                  @delete="handleDeleteComponent"
                  @update="handleUpdateComponent" />
              </template>
            </draggable>
          </div>
        </div>
      </div>

      <!-- 属性面板 -->
      <div class="property-panel">
        <template v-if="selectedComponent">
          <el-tabs>
            <el-tab-pane label="属性">
              <component
                :is="getPropertyEditor"
                :value="selectedComponent.props"
                @update="handleUpdateProps" />
            </el-tab-pane>
            <el-tab-pane label="样式">
              <style-editor
                :value="selectedComponent.style"
                @update="handleUpdateStyle" />
            </el-tab-pane>
            <el-tab-pane label="事件">
              <event-editor
                :value="selectedComponent.events"
                @update="handleUpdateEvents" />
            </el-tab-pane>
          </el-tabs>
        </template>
        <div v-else class="empty-tip">
          请选择一个组件进行编辑
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Back, 
  View, 
  Check, 
  Position // 使用 Position 图标
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { v4 as uuidv4 } from 'uuid'
import { useHistoryStore } from '@/stores/history'
import { basicComponents, advancedComponents, propertyEditors } from './config/components'
import ComponentWrapper from './components/ComponentWrapper.vue'
import StyleEditor from './components/StyleEditor.vue'
import EventEditor from './components/EventEditor.vue'

const router = useRouter()
const route = useRoute()
const historyStore = useHistoryStore()

const pageData = ref({
  id: '',
  title: '',
  components: []
})

const selectedComponent = ref(null)
const isDragging = ref(false)

// 视图模式
const viewMode = ref('pc')

// 画布样式
const canvasStyle = computed(() => ({
  width: viewMode.value === 'pc' ? '100%' : '375px',
  minHeight: '100%',
  margin: '0 auto',
  transition: 'all 0.3s'
}))

// 标尺相关
const rulerH = ref(null)
const rulerV = ref(null)
const rulerHCanvas = ref(null)
const rulerVCanvas = ref(null)
const scale = 1 // 缩放比例
const unit = 10 // 最小刻度单位

// 鼠标位置指示器
const mouseX = ref(0)
const mouseY = ref(0)
const showIndicator = ref(false)

// 获取页面数据
const getPageData = async () => {
  if (route.params.id === 'new') return

  try {
    // TODO: 调用接口获取页面数据
    const response = await fetch(`/api/pages/${route.params.id}`)
    const data = await response.json()
    pageData.value = data
  } catch (error) {
    console.error('获取页面数据失败:', error)
  }
}

// 克隆组件
const handleClone = (component) => {
  console.log('Cloning component:', component) // 添加日志
  return {
    id: uuidv4(),
    type: component.type,
    props: { ...component.props },
    style: {
      position: 'relative',
      width: '200px',
      height: 'auto'
    },
    events: {}
  }
}

// 选择组件
const handleSelectComponent = (component) => {
  if (isDragging.value) return
  selectedComponent.value = component
}

// 更新组件
const handleUpdateComponent = (component) => {
  const index = pageData.value.components.findIndex(c => c.id === component.id)
  if (index > -1) {
    pageData.value.components[index] = component
    historyStore.pushHistory(pageData.value)
  }
}

// 删除组件
const handleDeleteComponent = (component) => {
  const index = pageData.value.components.findIndex(c => c.id === component.id)
  if (index > -1) {
    pageData.value.components.splice(index, 1)
    selectedComponent.value = null
    historyStore.pushHistory(pageData.value)
  }
}

// 获取属性编辑器组件
const getPropertyEditor = computed(async () => {
  if (!selectedComponent.value) return null
  const editor = propertyEditors[selectedComponent.value.type]
  if (editor) {
    const module = await editor()
    return module.default
  }
  return null
})

// 更新组件属性
const handleUpdateProps = (props) => {
  if (!selectedComponent.value) return
  selectedComponent.value.props = { ...props }
  // 触发更新
  pageData.value.components = [...pageData.value.components]
}

// 更新样式
const handleUpdateStyle = (style) => {
  if (selectedComponent.value) {
    selectedComponent.value.style = style
    handleUpdateComponent(selectedComponent.value)
  }
}

// 更新事件
const handleUpdateEvents = (events) => {
  if (selectedComponent.value) {
    selectedComponent.value.events = events
    handleUpdateComponent(selectedComponent.value)
  }
}

// 拖拽开始
const handleDragStart = (event) => {
  console.log('Drag start:', event) // 添加日志
  isDragging.value = true
}

// 拖拽结束
const handleDragEnd = (event) => {
  console.log('Drag end:', event) // 添加日志
  isDragging.value = false
  if (event.added) {
    const newComponent = event.added.element
    if (newComponent) {
      if (!newComponent.id) {
        newComponent.id = uuidv4()
      }
      if (!newComponent.style) {
        newComponent.style = {
          position: 'relative',
          width: '200px',
          height: 'auto'
        }
      }
      historyStore.pushHistory(pageData.value)
    }
  }
}

// 返回列表
const handleBack = () => {
  router.push('/page-builder/list')
}

// 预览页面
const handlePreview = () => {
  if (!pageData.value.id) {
    ElMessage.warning('请先保存页面')
    return
  }
  router.push(`/page-builder/preview/${pageData.value.id}`)
}

// 保存页面
const handleSave = async () => {
  try {
    // TODO: 调用接口保存页面数据
    const response = await fetch('/api/pages', {
      method: pageData.value.id ? 'PUT' : 'POST',
      body: JSON.stringify(pageData.value)
    })
    const data = await response.json()
    pageData.value.id = data.id
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存页面失败:', error)
    ElMessage.error('保存失败')
  }
}

// 绘制标尺
const drawRuler = () => {
  const hCtx = rulerHCanvas.value.getContext('2d')
  const vCtx = rulerVCanvas.value.getContext('2d')
  const hWidth = rulerH.value.clientWidth
  const vHeight = rulerV.value.clientHeight

  // 设置canvas尺寸
  rulerHCanvas.value.width = hWidth * window.devicePixelRatio
  rulerHCanvas.value.height = 20 * window.devicePixelRatio
  rulerVCanvas.value.width = 20 * window.devicePixelRatio
  rulerVCanvas.value.height = vHeight * window.devicePixelRatio

  // 设置样式
  const rulerStyle = {
    font: '10px Inter, -apple-system, sans-serif',
    lineWidth: 1,
    strokeStyle: '#ccc',
    fillStyle: '#666'
  }

  // 应用样式
  Object.assign(hCtx, rulerStyle)
  Object.assign(vCtx, rulerStyle)

  // 缩放以适应设备像素比
  hCtx.scale(window.devicePixelRatio, window.devicePixelRatio)
  vCtx.scale(window.devicePixelRatio, window.devicePixelRatio)

  // 清空画布
  hCtx.clearRect(0, 0, hWidth, 20)
  vCtx.clearRect(0, 0, 20, vHeight)

  // 绘制水平标尺
  for (let i = 0; i < hWidth; i += unit) {
    const x = i * scale
    const isMainScale = i % 100 === 0
    const isHalfScale = i % 50 === 0
    
    hCtx.beginPath()
    hCtx.moveTo(x + 0.5, 20)
    hCtx.lineTo(x + 0.5, isMainScale ? 0 : (isHalfScale ? 8 : 14))
    hCtx.stroke()

    if (isMainScale) {
      hCtx.save()
      hCtx.fillStyle = '#666'
      hCtx.textAlign = 'center'
      hCtx.fillText(i.toString(), x, 7)
      hCtx.restore()
    }
  }

  // 绘制垂直标尺
  for (let i = 0; i < vHeight; i += unit) {
    const y = i * scale
    const isMainScale = i % 100 === 0
    const isHalfScale = i % 50 === 0

    vCtx.beginPath()
    vCtx.moveTo(20, y + 0.5)
    vCtx.lineTo(isMainScale ? 0 : (isHalfScale ? 8 : 14), y + 0.5)
    vCtx.stroke()

    if (isMainScale) {
      vCtx.save()
      vCtx.fillStyle = '#666'
      vCtx.translate(7, y)
      vCtx.rotate(-Math.PI / 2)
      vCtx.textAlign = 'center'
      vCtx.fillText(i.toString(), 0, 0)
      vCtx.restore()
    }
  }
}

// 处理画布滚动
const handleCanvasScroll = (e) => {
  rulerH.value.scrollLeft = e.target.scrollLeft
  rulerV.value.scrollTop = e.target.scrollTop
}

// 处理画布鼠标移动
const handleCanvasMouseMove = (e) => {
  const rect = e.currentTarget.getBoundingClientRect()
  mouseX.value = Math.round(e.clientX - rect.left - 20)
  mouseY.value = Math.round(e.clientY - rect.top - 20)
  showIndicator.value = true
}

// 处理画布鼠标离开
const handleCanvasMouseLeave = () => {
  showIndicator.value = false
}

// 监听窗口大小变化
const handleResize = () => {
  drawRuler()
}

onMounted(() => {
  getPageData()
  drawRuler()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.page-editor {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.editor-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--el-border-color);
  background-color: #fff;
}

.editor-header .left,
.editor-header .right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor-header .center {
  display: flex;
  align-items: center;
}

.editor-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.component-list {
  width: 260px;
  padding: 16px;
  border-right: 1px solid var(--el-border-color);
  background-color: #fff;
  overflow-y: auto;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  margin-bottom: 8px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  cursor: move;
}

.component-item:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

.canvas {
  position: relative;
  flex: 1;
  padding: 20px;
  overflow: hidden;
}

.ruler-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.ruler {
  position: absolute;
  background: #fff;
  border: none;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
  z-index: 2;
}

.ruler-h {
  top: 0;
  left: 20px;
  right: 0;
  height: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.ruler-v {
  top: 20px;
  left: 0;
  width: 20px;
  bottom: 0;
  border-right: 1px solid #e4e7ed;
}

.ruler-corner {
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  background: #fff;
  border: none;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.ruler-indicator {
  position: absolute;
  pointer-events: none;
  z-index: 4;
}

.ruler-line {
  position: absolute;
  background-color: var(--el-color-primary);
  opacity: 0.5;
}

.ruler-h .ruler-line {
  width: 1px;
  height: 100vh;
  left: 0;
  top: 0;
}

.ruler-v .ruler-line {
  height: 1px;
  width: 100vw;
  top: 0;
  left: 0;
}

.ruler-indicator-value {
  position: absolute;
  background-color: var(--el-color-primary);
  color: #fff;
  padding: 1px 4px;
  border-radius: 2px;
  font-size: 11px;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transform: scale(0.9);
  transform-origin: center;
}

.ruler-h .ruler-indicator-value {
  top: 24px;
  left: 50%;
  transform: translateX(-50%);
}

.ruler-v .ruler-indicator-value {
  left: 24px;
  top: 50%;
  transform: translateY(-50%);
}

.canvas-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow: auto;
  background-color: #f5f7fa;
}

.canvas-wrapper.mobile {
  display: flex;
  justify-content: center;
  background: #f5f5f5;
}

.canvas-container {
  position: relative;
  min-height: calc(100vh - 200px);
  background-color: #fff;
  background-image: 
    linear-gradient(to right, #f0f2f5 1px, transparent 1px),
    linear-gradient(to bottom, #f0f2f5 1px, transparent 1px);
  background-size: 20px 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.canvas-content {
  position: relative;
  min-height: 300px;
  padding: 20px;
  height: 100%;
}

/* 空画布提示 */
.canvas-content:empty::before {
  content: '拖拽组件到这里';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #909399;
  font-size: 14px;
}

/* 移动端预览时的网格 */
.mobile .canvas-container {
  width: 375px;
  margin: 20px auto;
  border-radius: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background-size: 10px 10px; /* 移动端网格更小 */
}

/* 添加辅助线 */
.canvas-container::before,
.canvas-container::after {
  content: '';
  position: absolute;
  background-color: rgba(64, 158, 255, 0.15);
  z-index: 1;
}

/* 垂直中心线 */
.canvas-container::before {
  top: 0;
  left: 50%;
  width: 1px;
  height: 100%;
}

/* 水平中心线 */
.canvas-container::after {
  left: 0;
  top: 50%;
  width: 100%;
  height: 1px;
}

/* 网格覆盖层 */
.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 0;
}

/* 强调网格线（每5格） */
.grid-overlay::before,
.grid-overlay::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(to right, rgba(0, 0, 0, 0.05) 1px, transparent 1px),
    linear-gradient(to bottom, rgba(0, 0, 0, 0.05) 1px, transparent 1px);
  background-size: 100px 100px; /* 5 * 20px */
}

.property-panel {
  width: 300px;
  padding: 16px;
  border-left: 1px solid var(--el-border-color);
  background-color: #fff;
  overflow-y: auto;
}

.empty-tip {
  color: var(--el-text-color-secondary);
  text-align: center;
  margin-top: 100px;
}

.grid-system {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  pointer-events: none;
  padding: 0 12px;
}

.grid-column {
  flex: 1;
  margin: 0 6px;
  background-color: rgba(0, 160, 233, 0.05);
  border-left: 1px dashed rgba(0, 160, 233, 0.1);
  border-right: 1px dashed rgba(0, 160, 233, 0.1);
}

.row-container {
  min-height: 50px;
  width: 100%;
}

.component-container {
  position: relative;
  min-height: 50px;
  padding: 4px;
}

/* 拖拽时的样式 */
.sortable-ghost {
  opacity: 0.5;
  background: var(--el-color-primary-light-9);
  border: 2px dashed var(--el-color-primary);
}

.sortable-drag {
  opacity: 0.8;
}
</style> 